package com.m4f.fse.web.filters;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserServiceFactory;

public class AdminUserFilter implements Filter {
	
	private Set<String> grantedAccountsTable;
	
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain filterChain) throws IOException, ServletException {
		HttpServletResponse res = (HttpServletResponse)response;
		if(!this.accessGranted(UserServiceFactory.getUserService().getCurrentUser())) {
			res.sendError(res.SC_FORBIDDEN);
		} else {
			filterChain.doFilter(request, response);
		}
		
	}

	private boolean accessGranted(User user) {
		if(user!=null) {
			if(!this.grantedAccountsTable.contains(user.getEmail())) {
				return false;
			}
		}
		return true;
	}
	
	@Override
	public void init(FilterConfig config) throws ServletException {
		grantedAccountsTable = new HashSet<String>();
	    String bannedSites =
	      config.getInitParameter("grantedAccounts");
	    // Default token set: white space.
	    StringTokenizer tok = new StringTokenizer(bannedSites);
	    while(tok.hasMoreTokens()) {
	      String grantedAccount = tok.nextToken();
	      grantedAccountsTable.add(grantedAccount);
	    }
	}

}